/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import entity.Event;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;


/**
 *
 * @author MONESI
 */
public class ForecastEngine  {
    
    private ArrayList <String> high= new ArrayList ();
    private ArrayList <String> low= new ArrayList ();
    private ArrayList <String> date= new ArrayList ();
    int ok=0;
    Date data = new Date();
    
    public ForecastEngine(){
        
    }
    
    public void weather (Event ev) {
        try {
        ArrayList <String> weather= new ArrayList ();
    
        String place = ev.getPlace();
        //String URL ="http://api.openweathermap.org/data/2.5/forecast?q=London,us&mode=xml";
        String URL = "http://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='"+place+"')&format=xml";
        //String URL = "http://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='London')&format=xml";
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(URL);
        doc.getDocumentElement().normalize();
        NodeList nList = doc.getElementsByTagName("yweather:forecast");

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                high.add(eElement.getAttribute("high"));
                low.add(eElement.getAttribute("low"));
                weather.add(eElement.getAttribute("text"));
                date.add(eElement.getAttribute("date"));
                
                }
        }
        
        if(!weather.isEmpty()){
                for(int i=0;i<5 && ok==0 ;i++){
                    if(data.getDate()+i==ev.getDate().getDate()){
                        ev.setWeather(weather.get(i));
                        ok=1;
                    }
                }
                if(ok==0)
                     ev.setWeather("Not Available Yet");
                
        }  
        
        
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}
